package person.drf.shop.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import person.drf.common.to.es.SkuEsModel;
import person.drf.shop.search.config.ElasticsearchConfig;
import person.drf.shop.search.constant.EsContant;
import person.drf.shop.search.service.MallSearchService;
import person.drf.shop.search.vo.SearchParm;
import person.drf.shop.search.vo.SearchResult;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchSericeImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    //接受一个检索参数请求类
    //返回检索结果
    @Override
    public SearchResult search(SearchParm searchParm) {
        // 动态构建出需要查询的DSL语句
        SearchResult searchResult = null;
        //1.准备检索请求
        SearchRequest searchRequest = BuilderSearchRequest(searchParm);
        try {
            //2.执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);
            searchResult = BuildeSearchResult(response,searchParm);
            //3.分析响应数据，封装成我们需要的格式
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    // 准备我们的检索请求
    private SearchRequest BuilderSearchRequest(SearchParm searchParm) {
        //所有请求条件都要从SearchSourceBuilder里面构建
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //1. 模糊匹配 ，过滤（按照属性，分类，品牌，价格区间，库存）
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must - 模糊匹配
        if(!StringUtils.isEmpty(searchParm.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParm.getKeyword()));

        }
        //1.2 filter - 过滤  -  按照三级分类id查询
        if(searchParm.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParm.getCatalog3Id()));
        }
        //1.2 filter - 过滤  -  品牌id（可以有多个）
        if(searchParm.getBrandId()!=null && searchParm.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termQuery("brandId",searchParm.getBrandId()));
        }
        //1.2 filter - 过滤  - 价格区间
        if(!StringUtils.isEmpty(searchParm.getSkuPrice())){
           // 约定：_1000  1_1000 1_ 区间字符串
            RangeQueryBuilder rangQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParm.getSkuPrice().split("_");
            if(s.length==2){
                //区间 1_1000
                rangQuery.gt(s[0]).lt(s[1]);
            }else if(s.length==1){
                if(searchParm.getSkuPrice().startsWith("_")){
                    // _1000
                    rangQuery.lt(s[0]);
                }if(searchParm.getSkuPrice().endsWith("_")){
                    // 1000_
                    rangQuery.lt(s[0]);
                }
            }
            boolQuery.filter(rangQuery);
        }
        if(searchParm.getAttrs()!=null && searchParm.getAttrs().size()>0){
            //约定属性传递 attrs=1_5寸:8寸&attrs=2_16G:8G
            for (String attrStr : searchParm.getAttrs()) {
                BoolQueryBuilder nestBoolQuery= QueryBuilders.boolQuery();
                // 1_5寸:8寸
                String[] s = attrStr.split("_");
                String attrId = s[0];  //检索属性id
                String[] attrValues = s[1].split(":"); //检索属性值
                nestBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue",attrValues));
                //关键的： 每一个属性都生成一个对应的nest查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }
        //1.2 filter - 过滤  -  是否有库存
        if(searchParm.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParm.getHasStock()==1));
        }

        // bool查询构建完成！
        sourceBuilder.query(boolQuery);

        /*
        *   第二部分： 排序，分页 ，高亮
        */
        //2.1 排序
        if(!StringUtils.isEmpty(searchParm.getSort())){
            //约定 传递sort=hotScore_asc/desc
            String[] s = searchParm.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")?SortOrder.ASC: SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //2.2 分页

        sourceBuilder.from((searchParm.getPageNum()-1)*EsContant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsContant.PRODUCT_PAGESIZE);  //常量已经定义好 -  6个
        //2.3 高亮
        //1.1 must - 模糊匹配
        if(!StringUtils.isEmpty(searchParm.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        // 第三部分：聚合分析
        // 3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 品牌聚合的子聚合
        //brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        // 3.2 分类聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        // 分类聚合的子聚合
        catelog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catelog_agg);

        // 3.3 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 属性聚合子聚合
        // 聚合当前所有attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 聚合当前attr的 名字name 与 值value
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.Value").size(1));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

//        打印语句
//        String s = sourceBuilder.toString();
//        System.out.println("构建的DSL:"+s);
        // 执行查询
        SearchRequest searchRequest = new SearchRequest(new String[]{EsContant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
    // 封装响应结果数据
    private SearchResult BuildeSearchResult(SearchResponse response, SearchParm searchParm) {
        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();  //总信息体
        // 1.获取全部商品记录
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if(hits.getHits()!=null && hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮属性
                if(!StringUtils.isEmpty(searchParm.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                skuEsModels.add(esModel);
            }
        }
        result.setProducts(skuEsModels);

        // 2.当前所有商品涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 3.当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            //得到品牌名字
            //String brand_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            //得到品牌图片
            String brand_img_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            //brandVo.setBrandName(brand_name_agg);
            brandVo.setBrandImg(brand_img_agg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4.当前所有商品涉及到的所有分类信息
        List<SearchResult.AttrVo> attrVos  = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            //得到属性名字
            String attr_name = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //得到属性所有值
            List<String> attr_value = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;

            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attr_name);
            attrVo.setAttrValue(attr_value);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //==========  分页信息  =============
        // 分页信息 -- 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 分页信息 -- 总页码(需要计算)
        int totalPage = (int)total%EsContant.PRODUCT_PAGESIZE==0?
                (int)total%EsContant.PRODUCT_PAGESIZE:((int)total%EsContant.PRODUCT_PAGESIZE+1);
        result.setTotalPage(totalPage);

        // 分页信息 -- 当前页码
        result.setPageNum(searchParm.getPageNum());

        // 分页信息 -- 页码数组
        List<Integer> pageNavs = new ArrayList<>();
        for (int i=1;i<=totalPage;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //System.out.println(result);
        return result;
    }
}
